const express = require('express')
// 生成ID
// const { v4: uuidv4 } = require('uuid')
// 引入jwt token工具
const JwtUtil = require('../../utils/jwt')

const router = express.Router()
// 一级路由： /user
// 二级路由： /register
// http://127.0.0.1:3005/user/register
// 导入已封装的数据函数
const db = require('../../config/db.js')
const config = require('../../config/require')
const HostUrl = `${config.PROTOCOL}://${config.HOST}:${config.PORT}`


//上传图片的包
let multer = require('multer')

// 通过filename属性定制
let storage = multer.diskStorage({
    // 保存的路径
    destination: function (req, file, callback) {
        callback(null, 'public/uploads/')
    },
    filename: function (req, file, callback) {
        // 将保存文件名设置为 字段名 + 时间戳，比如 logo-1478521468943
        let suffix = file.mimetype.split('/')[1]; //获取文件格式
        callback(null, file.fieldname + '-' + Date.now() + '.' + suffix);
    }
});

//生成的图片放入uploads文件夹下
let upload = multer({
    storage: storage
})


// 添加
router.post('/addUser', function (req, res) {
    let userName = req.body.userName
    let password = req.body.passWord
    let phone = req.body.phone
    let id = req.body.id
    let balance = 0
    let touxiang = `${HostUrl}/static/uploads/touxiang.png`
    // console.log(userName,password,phone,id);
    // console.log(req.body);
    
    let sql = 'select  * from user where userName="'+userName+'" or phone ="'+phone+'"';
    db.query(sql, function (err, rows) {
        if (err) {
            res.send({
                code: -1,
                msg: '查询失败'
            })
        } else {
            if (rows && rows.length !=0) {
                let [user] = rows
                if (user.userName == userName || user.phone == phone) {
                    res.send({
                        code: 201,
                        msg: '用户已存在'
                    })
                }else {
                    res.send({
                        code:501,
                        msg:'后端异常',
                        rows
                    })
                }
            }
         else {
            let addSql = 'insert into user(userName,passWord,phone,id,balance,touxiang) values("' + userName + '","' + password + '","' + phone + '","' + id + '","' + balance + '","' + touxiang + '")'
            db.query(addSql,  (err) => {
                if (err) {
                    res.send({
                        code: -1,
                        msg: '注册失败'
                    })
                } else {
                    res.send({
                        code: 200,
                        msg: '注册成功'
                    });
                }
            })
        }
        }
    })
    
})


// 查询数据(登录)
router.post('/login', function (req, res) {
    // let userName = req.body.userName;
    let passWord = req.body.passWord;
    let userName = req.body.userName;
    let phone = req.body.phone;
    // 查询用户表
    let user_check_sql = 'select * from user where passWord="' + passWord + '" and userName="' + userName + '" or phone = "' + phone + '"';

    db.query(user_check_sql, (err, rows) => {
        if (err) {
            res.send({
                code: -1,
                msg: '登录失败'
            })
        } else {
            if (rows && rows.length == 0) {
                res.send({
                    code: 404,
                    msg: '账号或密码错误'
                });
            } else {
                let [{ id, userName, phone,balance,touxiang }] = rows;
                // 将用户id传入并生成token
                let jwt = new JwtUtil(id);
                // 获取token
                let token = jwt.generateToken();
                // 将 token 返回给客户端
                res.send({
                    code: 200,
                    msg: '登录成功',
                    token,
                    userName,
                    phone,
                    id,
                    balance,
                    touxiang
                });
            }
        }
    })
})

// 删除
router.post('/delete_user',function(req,res) {
    let id = req.body.id
    let sql = 'select  * from user where id="'+id+'"';
    db.query(sql,function(err,rows) {
        if (err) {
            res.send({
                code: -1,
                msg: '查询失败'
            })
        }else {
            let delect_sql =  'delete  from user where id = "'+id+'"'
    db.query(delect_sql,(err) => {
        if(err) {
            res.send({
                code:-1,
                mes:'删除失败'
            })
        }else {
            res.send({
                code:200,
                msg:'删除成功'
            })
        }
    })
        }
    })
})

// // 修改密码
router.post('/updataPassWord',function(req,res) {
    let id = req.body.id
    let passWord = req.body.passWord
    let sql = 'select  * from user where id="'+id+'"';
    db.query(sql,function(err,rows) {
        if (err) {
            res.send({
                code: -1,
                msg: '查询失败'
            })
        }else {
            let updataSql = 'update user set password="'+passWord+'" where id="'+id+'"'
            db.query(updataSql,  (err) => {
                if (err) {
                    res.send({
                        code: -1,
                        msg: '修改密码失败'
                    })
                } else {
                    res.send({
                        code: 200,
                        msg: '修改密码成功'
                    });
                }
            })
        }
    })

}) 


// 更新余额
router.post('/updataBalance',function(req,res) {
    let id = req.body.id
    let balance = req.body.balance
    let sql = 'select  * from user where id="'+id+'"';

    db.query(sql,function(err,rows) {
        if (err) {
            res.send({
                code: -1,
                msg: '查询失败'
            })
        }else {
            let updataSql = 'update user set balance="'+balance+'" where id="'+id+'"'
            db.query(updataSql,  (err) => {
                if (err) {
                    res.send({
                        code: -1,
                        msg: '余额添加失败'
                    })
                } else {
                    res.send({
                        code: 200,
                        msg: '余额添加成功'
                    });
                }
            })
        }
    })
})

// 查询数据
router.get('/check',function(req,res){
    let check_sql = 'select  * from user'
    db.query(check_sql,function(err,rows) {
        if(err) {
            res.send({
                code: -1,
                msg:'查询失败'
            })
        }else {
            res.send({
                code: 200,
                msg:'查询成功',
                rows
            })
        }
    })
})

router.post('/changeImg', upload.single('photo'), function (req, res) {
    let id = req.body.id
    // 接收前端的文件
    let file = req.file
    // 定义存在在服务器的图片的路径（存在数据库的路径）
    let url = `${HostUrl}/static/uploads/${file.filename}`

    let sql = 'select  * from user where id="'+id+'"';
    db.query(sql,function(err,rows) {
        if (err) {
            res.send({
                code: -1,
                msg: '查询失败'
            })
        }else {
            let updataSql = 'update user set touxiang="'+url+'" where id="'+id+'"'
            db.query(updataSql,  (err,rows) => {
                if (err) {
                    res.send({
                        code: -1,
                        msg: '修改头像失败'
                    })
                } else {
                    res.send({
                        code: 200,
                        msg: '修改头像成功',
                        rows
                    });
                }
            })
        }
    })
})


module.exports = router;